<template>
  <el-dialog
    title="库存统计"
    :model-value="dialogVisible"
    @update:model-value="$emit('update:dialogVisible', $event)"
    draggable
    width="1200px"
    top="5vh"
    :before-close="handleBeforeClose"
    custom-class="custom-dialog"
  >
    <div class="statistics-container">
      <!-- 时间筛选表单 -->
      <el-form :model="queryForm" inline>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="queryForm.startDate"
            type="date"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="queryForm.endDate"
            type="date"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchStatistics" :loading="loading">
            查询
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        max-height="500px"
        v-loading="loading"
      >
        <el-table-column
          prop="productName"
          label="物料名称"
          width="200"
          fixed="left"
          align="center"
        />
        <el-table-column
          prop="specification"
          label="规格型号"
          width="200"
          align="center"
        />
        <!-- 重量信息列组 -->
        <el-table-column
          label="重量（kg）"
          align="center"
          header-align="center"
        >
          <el-table-column
            prop="inAmount"
            label="入库"
            width="120"
            align="right"
            :formatter="formatNumber"
          />
          <el-table-column
            prop="outAmount"
            label="出库"
            width="120"
            align="right"
            :formatter="formatNumber"
          />
          <el-table-column
            prop="finalAmount"
            label="当前重量"
            width="134"
            align="right"
            :formatter="formatNumber"
          />
        </el-table-column>

        <!-- 件数信息列组 -->
        <el-table-column
          label="件数（pcs）"
          align="center"
          header-align="center"
        >
          <el-table-column
            prop="inPiece"
            label="入库"
            width="120"
            align="right"
            :formatter="formatNumber"
          />
          <el-table-column
            prop="outPiece"
            label="出库"
            width="120"
            align="right"
            :formatter="formatNumber"
          />
          <el-table-column
            prop="finalPiece"
            label="当前数量"
            width="134"
            align="right"
            :formatter="formatNumber"
          />
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button @click="closeDialog">关闭</el-button>
    </template>
  </el-dialog>
</template>
  
<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

export default defineComponent({
  props: {
    dialogVisible: Boolean,
  },
  emits: ["update:dialogVisible"],
  setup(props, { emit }) {
    const queryForm = ref({
      startDate: "",
      endDate: "",
    });
    const tableData = ref([]);
    const loading = ref(false);

    const formatNumber = (row: any, column: any, cellValue: number) => {
      return Number(cellValue).toLocaleString();
    };

    const handleBeforeClose = (done: Function) => {
      // 添加关闭前的确认逻辑（可选）
      done(); // 必须调用 done() 方法
      resetFilters();
    };

    const closeDialog = () => {
      resetFilters();
      emit("update:dialogVisible", false);
    };

    // 初始化日期范围
    const initDateRange = () => {
      const now = dayjs();
      queryForm.value.startDate = now.startOf("month").format("YYYY-MM-DD");
      queryForm.value.endDate = now.format("YYYY-MM-DD");
    };

    // 重置筛选条件
    const resetFilters = () => {
      initDateRange();
      tableData.value = [];
    };

    const handleDateChange = async () => {
      if (queryForm.value.startDate && queryForm.value.endDate) {
        await fetchStatistics();
      }
    };

    const fetchStatistics = async () => {
      if (!queryForm.value.startDate || !queryForm.value.endDate) {
        ElMessage.warning("请先选择时间范围");
        return;
      }

      try {
        loading.value = true;
        let data = JSON.stringify({
          startTime: `${queryForm.value.startDate} 00:00:00`,
          endTime: `${queryForm.value.endDate} 23:59:59`, // 能获取当天操作
        });
        console.log(data);
        const response = await request({
          method: "post",
          url: "/inventory/records/count",
          headers: {
            "Content-Type": "application/json",
          },
          data: data,
        });

        tableData.value = response.data.data;
      } catch (error) {
        console.error("获取统计失败:", error);
        ElMessage.error("获取统计信息失败");
      } finally {
        loading.value = false;
      }
    };

    // 添加 prop 变化监听
    watch(
      () => props.dialogVisible,
      (newVal) => {
        if (newVal) {
          initDateRange();
          fetchStatistics();
        } else {
          resetFilters();
        }
      }
    );

    return {
      queryForm,
      tableData,
      loading,
      formatNumber,
      handleBeforeClose,
      closeDialog,
      handleDateChange,
      fetchStatistics,
    };
  },
});
</script >

<style scoped>
.statistics-container {
  padding: 10px;
}
</style>